﻿using Castle.DynamicProxy;
using CNKI.TPI.Web.Admin.IBLL;
using CNKI.TPI.Web.Admin.Model;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Search.IBLL;
using CNKI.TPI.Web.Search.Model;
using KNet.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace CNKI.TPI.Web.UI.Controllers.Admin
{
    public class Admin_MultiDBPublishController : BaseController
    {
        //
        // GET: /Admin_MultiDBPublish/
        ISingleDBPublishService singleService = null;
        IMultiDBPublishService mService = null;
        ISearchService searchService = null;
        public Admin_MultiDBPublishController(IMultiDBPublishService mService, ISearchService searchService,  ISingleDBPublishService singleService )
        {
            this.mService = generator.CreateInterfaceProxyWithTarget<IMultiDBPublishService>(mService, new IInterceptor[] { new LogInterceptor() });
            this.searchService = generator.CreateInterfaceProxyWithTarget<ISearchService>(searchService, new IInterceptor[] { new LogInterceptor() });
            this.singleService = generator.CreateInterfaceProxyWithTarget<ISingleDBPublishService>(singleService, new IInterceptor[] { new LogInterceptor() });
        }
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 添加跨库分类
        /// </summary>
        /// <returns></returns>
        public ActionResult NewClassify()
        {
            ViewBag.ClassDB = searchService.GetUnionClass();
            ViewBag.DBConfig = searchService.GetUnionDBList();
            return PartialView("NewClassify");
        }
        /// <summary>
        /// 保存数据库分类
        /// </summary>
        /// <param name="name"></param>
        /// <param name="code"></param>
        ///   /// <param name="m">新增修改标识</param>
        /// <returns></returns>
        public bool DBClassSave(string name, string code, string isSave)
        {
            bool flage = false;
            DBCLASS obj = new DBCLASS();
            obj.ClassName = name;
            obj.ClassCode = code;
            flage = mService.SavetDBClass(obj, isSave);
            return flage;

        }
        /// <summary>
        /// 删除分类
        /// </summary>
        /// <param name="name"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool DBClassDel(string dbcode)
        {
            bool flage = false;
            dbcode = dbcode.Replace(',', '+');
            flage = mService.DeleteDBClass(dbcode);
            return flage;

        }
        /// <summary>
        /// 添加跨库数据库页面
        /// </summary>
        /// <returns></returns>
        public ActionResult DBClassify(string code)
        {
            ViewBag.ClassCode = code;

            ViewBag.publishClass = searchService.GetUnionClass();
            return PartialView("DBClassify");
        }
        /// <summary>
        /// 获取分类下的数据库
        /// </summary>
        /// <param name="dbcode"></param>
        /// <returns></returns>
        public JsonResult DBList(string dbcode)
        {
            var res = new JsonResult();
            IList<DBCONFIG> list = searchService.GetUnionDBList(dbcode);

            if (list != null && list.Count > 0)
            {
                res.Data = list;
            }
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。  
            return res;
        }
        /// <summary>
        /// 获取已经发布的数据库
        /// </summary>
        /// <returns></returns>
        public JsonResult GetPublishDB()
        {
            var res = new JsonResult();
            IList<SYS_CMS_DATABASE> list = mService.GetPublishDBList();

            if (list != null && list.Count > 0)
            {
                res.Data = list;
            }
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。  
            return res;
        }
        /// <summary>
        /// 保存分类下的数据库
        /// </summary>
        /// <param name="name"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        ///         
        [HttpPost]
        public bool SaveDBUnderClass(string code, IList<DBCONFIG> list)
        {
            bool flage = true;
            flage = mService.UpdateDBConfig(code, list);
            return flage;
        }
        public ActionResult DBMapping()
        {
            return PartialView("DBMapping");
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        ///  
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Search(FormCollection form)
        {
            int pageIndexNow = 1;// 当前页   
            string type = "all";
            string name = "";
            if (!String.IsNullOrEmpty(Request["pageIndexNow"]))
            {
                pageIndexNow = int.Parse(Request["pageIndexNow"]);
            }
            if (!String.IsNullOrEmpty(Request["type"]))
            {
                type = Request["type"];
            }
            if (!String.IsNullOrEmpty(Request["hiddendbname"]))
            {
                name = Request["hiddendbname"].ToString();
            }
            PageList(pageIndexNow, type, name);
            return PartialView("DBMappingResult");
        }
        private void PageList(int pageIndexNow, string type, string name)
        {
            int pageSize = 10;//每页显示记录数
            int sumPage = 0;//一共多少页
            int disPgae = 8;  //默认显示页数，当页数大于该数值时，按规定格式显示
            int count = 0;

            IList<SYS_CMS_DATABASE> list = mService.GetDBMappingList(pageIndexNow, pageSize, type, name, out count);
            if (list != null && list.Count > 0)
            {
                ViewBag.DbList = list;
            }
            sumPage = count / pageSize; //一共多少页
            if (count % pageSize != 0)
            {
                sumPage = sumPage + 1;
            }
            ColumnAliasHelper com = new ColumnAliasHelper();
            ViewBag.TotalPage = sumPage;
            ViewBag.PageList = com.GetPageList(pageIndexNow, sumPage, disPgae);
            ViewBag.PageNow = pageIndexNow;//当前页
            ViewBag.PageSize = pageSize;
            ViewBag.Count = count;

        }
        /// <summary>
        /// 获取所有映射字段
        /// </summary>
        /// <param name="DbID"></param>
        /// <returns></returns>
        public ActionResult MappingInfo(int DbID, string DbCode)
        {
            IList<SYS_CMS_US_FIELDMAP> list = mService.GetDBMapInfo(DbID);
            ViewBag.DbFieldList = list;
            ViewBag.DbID = DbID;
            ViewBag.DbCode = DbCode;
            //获取公共字段
            ViewBag.DbUSField = mService.GetUSFiled();
            //获取数据库的字段
            ViewBag.DbSelfField = mService.GetDBFiledByDbCode(DbCode);
            return PartialView("MappingEdit");
        }
        /// <summary>
        /// 删除映射字段
        /// </summary>
        /// <param name="SysID"></param>
        /// <returns></returns>
        public bool MappingDel(int SysID)
        {
            SYS_CMS_US_FIELDMAP obj = new SYS_CMS_US_FIELDMAP();
            obj.SysID = SysID;
            return mService.DeleteFIELDMAP(obj);
        }
        /// <summary>
        /// 保存映射字段
        /// </summary>
        /// <param name="dbfieldID"></param>
        /// <param name="usfield"></param>
        /// <param name="dbid"></param>
        /// <returns></returns>
        public int MappingSave(string dbfieldID, string usfield, string dbid, string flage, string sysid)
        {
            int m = mService.MappingSave(dbfieldID, usfield, dbid, flage, sysid);
            return m;
        }
        /// <summary>
        /// 跨库检索设置
        /// </summary>
        /// <returns></returns>
        public ActionResult MultiSearchColumn()
        {
            //获取公共字段
            ViewBag.DbUSField = mService.GetUSFiled();
            ViewBag.SearchField = searchService.GetUnionFieldList(FieldType.Search);
            getColumnInfo(FieldType.Search);
            return PartialView("MultiSearchColumn");
        }
        /// <summary>
        /// 跨库概览设置
        /// </summary>
        /// <returns></returns>
        public ActionResult MultiViewColumn()
        {
            //获取公共字段
            ViewBag.DbUSField = mService.GetUSFiled();
            ViewBag.ViewField = searchService.GetUnionFieldList(FieldType.Overview);
            getColumnInfo(FieldType.Overview);
            return PartialView("MultiViewColumn");
        }
        /// <summary>
        /// 跨库排序设置
        /// </summary>
        /// <returns></returns>
        public ActionResult MultiSortColumn()
        {
            //获取公共字段
            ViewBag.DbUSField = mService.GetUSFiled();
            ViewBag.SortField = searchService.GetUnionFieldList(FieldType.Sort);
            getColumnInfo(FieldType.Sort);
            return PartialView("MultiSortColumn");
        }
        /// <summary>
        /// 已经设置的显示名称及宽度
        /// </summary>
        /// <param name="type"></param>
        private void getColumnInfo(FieldType type)
        {
            IList<DBUSFIELD> listf = searchService.GetUnionFieldList(type);
            //显示名
            StringBuilder dispName = new StringBuilder();
            if (listf != null && listf.Count > 0)
            {
                dispName.Append('[');
                foreach (DBUSFIELD item in listf)
                {
                    string str = "{\"name\":\"" + item.RealFieldName + "\",\"displayname\":\"" + item.ShowFieldName + "\",\"displaywidth\":\"" + item.Width + "\"}";
                    dispName.Append(str).Append(',');
                }
                if (dispName != null)
                {
                    ViewBag.DispName = dispName.ToString().TrimEnd(',') + "]";
                }
                else
                {
                    ViewBag.DispName = "";
                }
            }

        }
        /// <summary>
        /// 保存检索字段
        /// </summary>
        /// <param name="Column"></param>
        /// <returns></returns>
        public bool SearchColumnSave(string Column)
        {
            int type = (int)FieldType.Search;
            return ColumnSave(Column, type);
        }
        /// <summary>
        /// 保存概览字段
        /// </summary>
        /// <param name="Column"></param>
        /// <returns></returns>
        public bool ViewColumnSave(string Column)
        {
            int type = (int)FieldType.Overview;
            return ColumnSave(Column, type);
        }
        /// <summary>
        /// 保存排序字段
        /// </summary>
        /// <param name="Column"></param>
        /// <returns></returns>
        public bool SortColumnSave(string Column)
        {
            int type = (int)FieldType.Sort;
            return ColumnSave(Column, type);
        }
        /// <summary>
        /// 保存设置的跨库字段
        /// </summary>
        /// <param name="Column"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private bool ColumnSave(string Column, int type)
        {
            bool m = false;
            IList<DBUSFIELD> list = new List<DBUSFIELD>();
            if (Column != "")
            {
                string[] columnArray = Column.Split(',');
                foreach (string str in columnArray)
                {
                    DBUSFIELD obj = new DBUSFIELD();
                    string[] stritem = str.Split('#');
                    IList<SYS_CMS_US_FIELD> listobj = mService.GetUSFieldByName(stritem[0]);
                    if (listobj != null && listobj.Count > 0)
                    {
                        obj.DataType = listobj[0].DataType;
                        obj.FieldID = listobj[0].SYSID;
                    }
                    else
                    {
                        m = false;
                        return m;
                    }
                    obj.ShowFieldName = stritem[1];
                    obj.RealFieldName = stritem[0];
                    if (stritem[2] != "")
                        obj.Width = int.Parse(stritem[2]);
                    else
                        obj.Width = 0;
                    obj.FieldType = type;
                    list.Add(obj);
                }
                m = mService.SavetUsField(list, type);
            }
            return m;

        }
        /// <summary>
        /// 生成drs文件
        /// </summary>
        /// <returns></returns>
        public bool CreateDrsXmlM()
        {
            DRSManager drsm = new DRSManager();
            return drsm.UpdateMultiDRSInfo();
        }
        public ActionResult ExternalResourcesIndex()
        {
            return PartialView("ExternalResources");
        }
        public ActionResult SearchExternal(FormCollection form)
        {
            int pageIndexNow = 1;// 当前页   
            string name = "";
            if (!String.IsNullOrEmpty(Request["pageIndexNow"]))
            {
                pageIndexNow = int.Parse(Request["pageIndexNow"]);
            }
          
            if (!String.IsNullOrEmpty(Request["hiddendbname"]))
            {
                name = Request["HiddenDbName"].ToString();
            }
          
            int pageSize = 10;//每页显示记录数
            int sumPage = 0;//一共多少页
            int disPgae = 8;  //默认显示页数，当页数大于该数值时，按规定格式显示
            int count = 0;
            IList<SYS_CMS_DATABASE> list = singleService.GetDBListPageSize(pageIndexNow, pageSize, out count, name);
            if (list != null && list.Count > 0)
            {
                ViewBag.DbList = list;
            }
            sumPage = count / pageSize; //一共多少页
            if (count % pageSize != 0)
            {
                sumPage = sumPage + 1;
            }
            ColumnAliasHelper com = new ColumnAliasHelper();
            ViewBag.TotalPage = sumPage;
            ViewBag.PageList = com.GetPageList(pageIndexNow, sumPage, disPgae);
            ViewBag.PageNow = pageIndexNow;//当前页
            ViewBag.PageSize = pageSize;
            ViewBag.Count = count;
            return PartialView("ExternalResult");

        }
        /// <summary>
        /// 保存数据及字段信息
        /// </summary>
        /// <param name="dbobj"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool DealDataBaseInfo(SYS_CMS_DATABASE dbobj,IList<SYS_CMS_DATABASE_FIELD> list,string fieldstr)
        {
            return mService.DealDataBaseInfo(dbobj,list,fieldstr);
        }
       /// <summary>
       /// 删除对应的数据库
       /// </summary>
       /// <param name="dbid"></param>
       /// <returns></returns>
        public bool DelDbAndFields(string dbid)
        {
            return mService.DelDbAndFields(dbid);

        }

        /// <summary>
        /// 获取数据库对应的字段信息
        /// </summary>
        /// <param name="dbcode"></param>
        /// <returns></returns>
        public JsonResult GetDBFieldsList(string dbcode)
        {
            var res = new JsonResult();
            IList<SYS_CMS_DATABASE_FIELD> list = mService.GetDBFiledByDbCode(dbcode);
            if (list != null && list.Count > 0)
            {
                res.Data = list;
            }
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。  
            return res;
        }
        /// <summary>
        /// 是否存在数据库
        /// </summary>
        /// <param name="name"></param>
        /// <param name="code"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public int IsExistsDB(string name,string code,int id)
        {
            return mService.IsExistDB(name,code,id);
        }
    }
}
